package com.dengcj.ecology.common;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.cloudstore.dev.api.util.Util_DataCache;
import weaver.general.BaseBean;

import java.util.HashMap;
import java.util.Map;

/**
 * @author dengchunjie
 * @Description: Ecology接口工具类
 * @date 2022/1/15 12:27
 */
public class EcologyApiUtil extends BaseBean {

    private final String ECOLOGY_HOST = "http://127.0.0.1";
    private final String ECOLOGY_API_APPID = "6EC751A6-728A-5A88-B5D1-54B3C14722D8";
    private String ECOLOGY_API_SECRET = "";
    private String ECOLOGY_API_SPK = "";

    // INSERT INTO ECOLOGY_BIZ_EC(ID,APPID,NAME) VALUES('EcologySelfUser','6EC751A6-728A-5A88-B5D1-54B3C14722D8','Ecology自调用');

    public EcologyApiUtil(){
        this.ECOLOGY_API_SECRET = Util_DataCache.getObjVal("ECOLOGY_API_SECRET").toString();
        this.ECOLOGY_API_SPK = Util_DataCache.getObjVal("ECOLOGY_API_SPK").toString();

        if(StrUtil.isBlank(this.ECOLOGY_API_SECRET) || StrUtil.isBlank(this.ECOLOGY_API_SPK)){
            this.ECOLOGY_API_SECRET = this.getPropValue("EcologyApiSelfUse","secret");
            this.ECOLOGY_API_SPK = this.getPropValue("EcologyApiSelfUse","spk");

            Util_DataCache.setObjVal("ECOLOGY_API_SECRET", this.ECOLOGY_API_SECRET);
            Util_DataCache.setObjVal("ECOLOGY_API_SPK", this.ECOLOGY_API_SPK);
        }
    }

    private void regist() {
        //获取当前系统RSA加密的公钥
        RSA rsa = new RSA();
        String publicKey = rsa.getPublicKeyBase64();
        String privateKey = rsa.getPrivateKeyBase64();
        // 调用ECOLOGY系统接口进行注册
        String data = HttpRequest.post(ECOLOGY_HOST + "/api/ec/dev/auth/regist")
                .header("appid",ECOLOGY_API_APPID)
                .header("cpk",publicKey)
                .timeout(3000)
                .execute().body();

        System.out.println(data);
    }

    private String getToken() {
        // 先从缓存中读取
        String token = Util_DataCache.getObjVal("ECOLOGY_API_TOKEN").toString();
        if(StrUtil.isNotBlank(token)){
            System.out.println("从缓存中读取Token:"+token);
            return token;
        }

        if(StrUtil.isBlank(this.ECOLOGY_API_SPK) || StrUtil.isBlank(this.ECOLOGY_API_SECRET)){
            System.out.println("spk:"+this.ECOLOGY_API_SPK+",secret:"+this.ECOLOGY_API_SECRET);
            return "";
        }

        // 公钥加密,所以RSA对象私钥为null
        RSA rsa = new RSA(null,this.ECOLOGY_API_SPK);
        //对秘钥进行加密传输，防止篡改数据
        String encryptSecret = rsa.encryptBase64(this.ECOLOGY_API_SECRET, CharsetUtil.CHARSET_UTF_8, KeyType.PublicKey);

        System.out.println("encryptSecret:"+encryptSecret);

        //调用ECOLOGY系统接口进行注册
        String data = HttpRequest.post(this.ECOLOGY_HOST+ "/api/ec/dev/auth/applytoken")
                .header("appid",this.ECOLOGY_API_APPID)
                .header("secret",encryptSecret)
                .header("time","3600")
                .execute().body();

        System.out.println(data);

        Map<String,Object> datas = JSONUtil.parseObj(data);
        token = StrUtil.nullToEmpty((String)datas.get("token"));

        System.out.println("从接口重新获取Token:"+token);

        // 写入缓存
        Util_DataCache.setObjVal("ECOLOGY_API_TOKEN", token,1500);
        return token;
    }

    /**
     * 通用的请求Ecoloyg接口方法
     * @param operUser 用户ID
     * @param url 接口地址
     * @param params 接口参数
     * @return
     */
    public String commonRequest(int operUser, String url, Map<String, Object> params){
        String result ="";

        Map<String, String> heads = new HashMap<>();
        String token = getToken();
        if(StrUtil.isBlank(token)){
            System.out.println("获取Ecology API token失败");
            return "";
        }
        heads.put("token", token);
        heads.put("appid", this.ECOLOGY_API_APPID);
        RSA rsa = new RSA(null, this.ECOLOGY_API_SPK);
        String secretUserid = rsa.encryptBase64(String.valueOf(operUser), CharsetUtil.CHARSET_UTF_8, KeyType.PublicKey);
        System.out.println(secretUserid);
        heads.put("userid", secretUserid);

        System.out.println("调用Ecology API requestParam:"+params.toString());
        try {
            System.out.println("调用Ecology API URL:"+this.ECOLOGY_HOST + url);
            result = HttpRequest.post(this.ECOLOGY_HOST + url)
                    .headerMap(heads, true)
                    //.body(requestBody)
                    .form(params)
                    .execute().body();

            System.out.println("调用Ecology API responseBody:"+result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static void main(String[] args) {
        EcologyApiUtil ecologyApiUtil = new EcologyApiUtil();
        ecologyApiUtil.regist();
    }
}
